/**
 * 
 */
package com.itboye.allshengmedical.sci.packet.resp;

import com.itboye.allshengmedical.sci.cmd.req.CmdType;

import android.util.Log;

/**
 * @author 贝贝 346551990@qq.com
 * @date 2016-12-9
 */
public class RespPacketParser {

	/**
	 * 转换成版本数据响应包
	 * 
	 * @param packet
	 * @return
	 */
	public static VersionRespPacket convertTo(BaseRespPacket packet) {

		if (packet.getCmdType() == CmdType.Version) {
			return new VersionRespPacket(packet);
		}

		return null;
	}

	public static BaseRespPacket parse(String packet) {
		BaseRespPacket respPacket = new BaseRespPacket();
		if (packet.length() < 6) {
			Log.d("serial", "数据包非法=>数据长度小于6");
			return null;
		}

		String start = packet.substring(0, 4);// 0-4 起始
		String dataLength = packet.substring(4, 6);// 0-2 数据长度
		int intLength = Integer.parseInt(dataLength, 16);// 解析成十进制

		if (packet.length() != intLength * 2 + 14) {
			Log.d("serial", "数据包非法=>数据长度期望为:" + (intLength * 2 + 14) + ",实际为:"
					+ packet.length());
			return null;
		}

		String content = packet.substring(6, 6 + intLength * 2);// 6 - len 数据
		String checksum = packet.substring(packet.length() - 8,
				packet.length() - 4);// 0-2 数据长度
		String end = packet.substring(packet.length() - 4, packet.length());// 0-2
																			// 数据长度

		respPacket.setStart(convertToByteArray(start));
		respPacket.setLen((byte) intLength);
		respPacket.setContent(convertToByteArray(content));
		// Log.e("hu..data", respPacket.getHexContent(index));
		respPacket.setCheckBit(convertToByteArray(checksum));
		respPacket.setEnd(convertToByteArray(end));

		return respPacket;
	}

	private static byte[] convertToByteArray(String hex) {

		if (hex.length() % 2 == 0) {
			int byteSize = hex.length() / 2;
			byte[] ret = new byte[byteSize];
		    char[] hexChars = hex.toCharArray();  
		    for (int i = 0; i < byteSize; i++) {  
		        int pos = i * 2;  
		        ret[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));  
		    }  

			return ret;
		}

		return null;
	}
	
	/** 
	 * Convert char to byte 
	 * @param c char 
	 * @return byte 
	 */  
	 private static byte charToByte(char c) {  
	    return (byte) "0123456789ABCDEF".indexOf(c);  
	}

}
